package cn.com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * Title: 检索基本类
 * </p>
 * <p>
 * Description:常用工具
 * </p>
 * <p>
 * Copyright: Copyright (c) suneasy 2010
 * </p>
 * <p>
 * Company: 138do
 * </p>
 * 
 * @author wsu
 * @version 2.1 2010/11/25 17:34:56 wangsu Exp $
 */

public class Tools {
	public Tools() {
	}

	/**
	 * 截NULL
	 * 
	 * @param str
	 * @return
	 */
	public static String RmNull(String str) { // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		return str;
	}

	/**
	 * 过滤 $%^*?+_',.等符号
	 * 
	 * @param str
	 * @return
	 */
	public static String RmFilter(String str) { // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		str = str.replace('<', ' ');
		str = str.replace('>', ' ');
		str = str.replace('"', ' ');
		str = str.replace('\'', ' ');
		str = str.replace('/', ' ');
		str = str.replace('%', ' ');
		str = str.replace(';', ' ');
		str = str.replace('(', ' ');
		str = str.replace(')', ' ');
		str = str.replace('&', ' ');
		str = str.replace('+', '_');

		return str;
	}

	/**
	 * 过滤 $%^*?+_',.等符号
	 * 
	 * @param str
	 * @return
	 */

	public static String RmFilter2(String str) { // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		str = str.replace('<', ' ');
		str = str.replace('>', ' ');
		str = str.replace('"', ' ');
		str = str.replace('\'', ' ');
		// str = str.replace('/',' ');
		str = str.replace('%', ' ');
		str = str.replace(';', ' ');
		str = str.replace('(', ' ');
		str = str.replace(')', ' ');
		str = str.replace('&', ' ');
		str = str.replace('+', '_');

		return str;
	}

	/**
	 * 读文件到缓冲里面
	 * 
	 * @param filePath
	 * @return
	 */
	public static StringBuffer readFile(String filePath) {
		// StringBuffer bStr = new StringBuffer();
		// String LineStr = "";
		// try {
		// System.setProperty("user.language", "zh");
		// System.setProperty("file.encoding", "GBK");
		// java.io.FileReader fr = new java.io.FileReader(filePath);
		//
		// java.io.BufferedReader br = new java.io.BufferedReader(
		// fr);
		// while ( (LineStr = br.readLine()) != null) {
		// bStr.append(LineStr +
		// System.getProperty("line.separator"));
		// }
		// br.close();
		// fr.close();
		// }
		// catch (Exception e) {
		// System.out.println(e.getMessage());
		// System.out.println("不能读取正文！");
		// }
		// return bStr;
		try {
			return readFile(filePath, "GBK");
		} catch (IOException ex) {
			System.out.println(ex);
			return null;
		}
	}

	public static void writeFile(String filePath, String contStr) {
		writeFile(filePath, contStr, "GBK");
	}

	public static void writeFile(String filePath, String contStr, String encoder) {
		try {
			java.io.FileOutputStream afile = new java.io.FileOutputStream(
					filePath);
			afile.write(contStr.getBytes(encoder));
			afile.close();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("Can't Written！");
		}
	}

	public static StringBuffer readFile(String filePath, String encoder)
			throws java.io.IOException {
		try {

			java.io.InputStream fis = new java.io.FileInputStream(filePath);
			byte[] b_all = new byte[fis.available()];
			byte[] readBytes = new byte[10240];
			int readInt, start = 0;
			while ((readInt = fis.read(readBytes)) != -1) {
				System.arraycopy(readBytes, 0, b_all, start, readInt);
				start += readInt;
			}
			fis.close();
			String str = new String(b_all, encoder);
			return new StringBuffer(str);
		} catch (IOException e) {
			System.out.println("read  the file " + filePath + " err:"
					+ e.toString());
			throw e;
		}

	}

	/**
	 * 日期格式化
	 * 
	 * @param date
	 *            需要格式化日期
	 * @param pattern
	 *            需要格式话的PATTERN
	 * @return 返回格式化的效果
	 */
	public static String dateToStr(Date date, String pattern) {
		java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat(
				pattern);
		return formater.format(date);
	}

	/**
	 * 日期格式化 判断日期是否超届
	 * 
	 * @param date
	 *            需要格式化日期
	 * @return 返回格式化的效果
	 */
	public static String dateFormat(String str) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format.parse(str);
			str = format.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
			str = "2010-02-19";
		}

		return str;
	}

	/**
	 * 替换字符窜，虽然1。4有功能，但为了能再1。2能用所以用此函数
	 * 
	 * @param source
	 * @param oldString
	 * @param newString
	 * @return
	 */
	public static String Replace(String source, String oldString,
			String newString) {
		StringBuffer output = new StringBuffer(); // define String Buffer
		int lengthOfSource = source.length(); // 源字符串长度
		int lengthOfOld = oldString.length(); // 老字符串长度
		int posStart = 0; // 开始搜索位置
		int pos; // 搜索到老字符串的位置
		while ((pos = source.indexOf(oldString, posStart)) >= 0) {
			output.append(source.substring(posStart, pos));

			output.append(newString);
			posStart = pos + lengthOfOld;
		}

		if (posStart < lengthOfSource) {
			output.append(source.substring(posStart));
		}

		return output.toString();
	}

	public static void mkDir(String filePath) {
		File file = new File(filePath);
		try {
			file.mkdirs();
			System.out.println("make dir ok!");
		} catch (Exception e) {
			System.out.println("mkdir error:" + e);
		}
	}

	/**
	 * 回车换行
	 * 
	 * @param Content
	 * @return
	 */
	public static String addBR(String Content) {
		String makeContent = "";
		StringTokenizer strToken = new StringTokenizer(Content, "\n");
		while (strToken.hasMoreTokens()) {
			makeContent = makeContent + strToken.nextToken() + "<br>";
		}
		makeContent = makeContent.replaceAll("  ", "　");
		return makeContent;
	}

	/**
	 * 字符集转换
	 * 
	 * @param s
	 * @return
	 */
	public static String ISO8859_1ToGBK(String s) {
		try {
			// s = new String(s.getBytes("ISO-8859-1"), "GBK");
		} catch (Exception e) {
			System.out.println("ISO8859_1ToGBK" + e);
		}
		return s;
	}

	/**
	 * 字符集转换
	 * 
	 * @param s
	 * @return
	 */
	public static String GBKToISO8859_1(String s) {
		try {
			// s = new String(s.getBytes("GBK"), "ISO-8859-1");
		} catch (Exception e) {
			System.out.println("GBKToISO8859_1" + e);
		}
		return s;
	}

	/**
	 * 替换字符缓冲中所有的标签
	 * 
	 * @param strb
	 *            缓冲
	 * @param sStr
	 *            原字符
	 * @param nString
	 *            新字符
	 * @return
	 */
	public static StringBuffer replaceAll(StringBuffer strb, String sStr,
			String nString) {
		int start = 0;
		while ((start = strb.indexOf(sStr, start)) > -1) {
			strb.replace(start, start + sStr.length(), nString);
			start = start + nString.length();
		}
		return strb;
	}

	/**
	 * 格式话法规，论文，专用
	 * 
	 * @param strb
	 *            需要格式的字符缓冲
	 * @return
	 */
	public static StringBuffer txtFormat(StringBuffer strb) {
		String LineStr = "";
		int s0 = 0;
		int s1 = 0;
		int s2 = 0;
		int s3 = 0;
		StringBuffer tmpBuffer = new StringBuffer();
		String lineSpr = System.getProperty("line.separator");
		while (strb.indexOf(lineSpr) > -1) {
			LineStr = strb.substring(0, strb.indexOf(lineSpr)); // 取一行
			strb.delete(0, strb.indexOf(lineSpr) + lineSpr.length()); // 删除这一行
			s0 = LineStr.indexOf("    "); // 四个空格
			s1 = LineStr.indexOf("      "); // 六个
			s2 = LineStr.indexOf("                                    "); // 36个
			s3 = LineStr.indexOf("<pre>");

			if (s3 == 0) {
				tmpBuffer.append(LineStr);
				while (strb.indexOf(lineSpr) > -1) {
					LineStr = strb.substring(0, strb.indexOf(lineSpr)); // 取一行
					strb.delete(0, strb.indexOf(lineSpr) + lineSpr.length()); // 删除这一行
					s3 = LineStr.indexOf("</pre>");
					tmpBuffer.append(LineStr + lineSpr);
					if (s3 == 0) {
						break;
					}
				}
			}

			if (s0 == 0) {
				if (s1 == 0) {
					if (s2 == 0) {
						tmpBuffer.append("<div align=right>" + LineStr.trim()
								+ "</div>");
					} else {
						tmpBuffer.append("<div  align=center><strong>"
								+ LineStr.trim() + "</strong></div>");
					}
				} else {
					tmpBuffer.append("　　" + LineStr.trim() + lineSpr + "<br>");
				}
			} else {
				tmpBuffer.append(LineStr + lineSpr + "<br>");
			}

			// tmpBuffer.append(LineStr);
		}
		return tmpBuffer;
	}

	/**
	 * 删除网页标签,包括<> 及里面的字符,只留中文
	 * 
	 * @param s
	 *            String
	 * @return String
	 */
	public static String rmHtml(String str) {
		if (str == null || str.equals("")) {
			str = "";
		}
		String regEx = "[=\\'^\"./%;&<>(A-Z)(a-z)]"; // 表示一个或多个a\p{Punct}

		Pattern p = Pattern.compile(regEx);

		Matcher m = p.matcher(str);

		str = m.replaceAll("");
		str = str.replaceAll(" ", "");
		return str;
	}

	// 过滤网页代码
	public static String rmHtml2(String page) {
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(page);
		page = m_html.replaceAll(""); // 过滤html标签

		return page;
	}

	public static void test(int arr[]) {
		int[] tempArr = new int[] { 1, 23, 4, 100, 222, 21 };
		// arr = new int [tempArr.length];
		for (int i = 0; i < tempArr.length; i++) {
			arr[i] = tempArr[i];
		}
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(1);
	}

	/**
	 * MD5加密
	 * 
	 * @param s
	 *            String
	 * @return String
	 */

	public static String toMD5(String str) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
		return new BigInteger(md.digest()).toString(16);
	}
	
	
	/**
	  * 获取加密后的字符串
	  * @param input
	  * @return
	  */
	 public static String stringMD5(String pw) {
	  try { 

	        // 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”） 
	        MessageDigest messageDigest =MessageDigest.getInstance("MD5"); 
	        // 输入的字符串转换成字节数组 
	        byte[] inputByteArray = pw.getBytes(); 
	        // inputByteArray是输入字符串转换得到的字节数组 
	        messageDigest.update(inputByteArray); 
	        // 转换并返回结果，也是字节数组，包含16个元素 
	        byte[] resultByteArray = messageDigest.digest(); 
	        // 字符数组转换成字符串返回 
	        return byteArrayToHex(resultByteArray); 
	     } catch (NoSuchAlgorithmException e) { 
	        return null; 
	     } 
	 }

	    public static String byteArrayToHex(byte[] byteArray) { 

	        // 首先初始化一个字符数组，用来存放每个16进制字符 
	        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' }; 
	        // new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）） 
	        char[] resultCharArray =new char[byteArray.length * 2]; 
	        // 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去 
	        int index = 0;
	        for (byte b : byteArray) { 
	           resultCharArray[index++] = hexDigits[b>>> 4 & 0xf]; 
	           resultCharArray[index++] = hexDigits[b& 0xf]; 
	        }
	        // 字符数组组合成字符串返回 
	        return new String(resultCharArray); 
	    }

	/***
	 * @param data
	 * @return
	 */
	public static String erpMD5(String data) {

		try {
			// 实例化一个指定摘要算法为MD5的MessageDigest对象
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			// 重置摘要以供再次使用
			algorithm.reset();
			// 使用bytes更新摘要
			try{ 
			   //最重要的是这句,需要加上编码类型
			   algorithm.update(data.getBytes("UTF-8")); 
	        } catch (Exception e) { 
	        	algorithm.update(data.getBytes()); 
	        } 
			// 使用指定的byte数组对摘要进行最的更新，然后完成摘要计算
			return toHexString(algorithm.digest(), "");
		} catch (NoSuchAlgorithmException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return "";
	}

	// 将字符串中的每个字符转换为十六进制
	private static String toHexString(byte[] bytes, String separator) {

		StringBuilder hexstring = new StringBuilder();
		for (byte b : bytes) {
			String hex = Integer.toHexString(0xFF & b);
			if (hex.length() == 1) {
				hexstring.append('0');
			}
			hexstring.append(hex);

		}

		return hexstring.toString();
	}
	
	/**
	 * copy 复制文件 oldPath 源文件 savePath 复制后文件地址
	 */

	public static void copyFile(String oldPath, String savePath) {

		try {
			// System.out.println(oldPath);
			// System.out.println(savePath);
			File temp = new File(oldPath);

			if (temp.isFile()) {
				FileInputStream input = new FileInputStream(temp);
				FileOutputStream output = new FileOutputStream(savePath);
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = input.read(b)) != -1) {
					output.write(b, 0, len);
				}
				output.flush();
				output.close();
				input.close();
			}

		} catch (Exception e) {
			System.out.println("copy file error" + e);
		}
	}

	/**
	 * isNumber 判断是否数字 s 不是返回0 容错处理
	 */

	public static int isNumber(String s) {
		int tempid = 0;
		try {
			tempid = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			tempid = 0;
		}
		return tempid;
	}

	/**
	 * isNumber 判断是否手机号s 不是返回0 容错处理
	 */

	public static String isMob(String s) {
		String tempid = "";
		try {
			String regex = "^1\\d{10}$";
			boolean isMob = s.matches(regex);
			if (isMob)
				tempid = s;
			else
				tempid = "";
		} catch (NumberFormatException e) {
			tempid = "";
		}
		return tempid;
	}

	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}

	/**
	 * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
	 * 
	 * @param s
	 *            需要得到长度的字符串
	 * @return i得到的字符串长度
	 */
	public static int strLength(String s) {
		if (s == null)
			return 0;
		char[] c = s.toCharArray();
		int len = 0;
		for (int i = 0; i < c.length; i++) {
			len++;
			if (!isLetter(c[i])) {
				len++;
			}
		}
		return len;
	}

}
